package test.myorm.chain.demo;

import java.lang.reflect.Method;
import java.util.Date;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import test.myorm.chain.Interceptor;
import test.myorm.chain.Invocation;

public class LogInterceptor implements Interceptor {

	@Override
	public Object invoke(Invocation invocation) {
		System.out.println("logInterceptor start...");
		Object result = invocation.invoke();
		System.out.println("logInterceptor end...");
		return result;
	}
	
	public static void main(String[] args) {
		UserService userService = (UserService)createProxy(new UserService());
		String name = userService.getName("zhangsan");
		System.out.println(name);
	}
	
	private static Object createProxy(Object obj) {
		Enhancer enhancer = new Enhancer();
	    enhancer.setSuperclass(obj.getClass());
	    enhancer.setCallback(new MethodInterceptor() {
			@Override
			public Object intercept(Object target, Method method, Object[] args, MethodProxy proxy) throws Throwable {
				System.out.println(new Date());
				return method.invoke(obj, args);
			}
		});
	    return enhancer.create();
	}

}
